package cn.edu.sdjzu.xg2106.service;

import cn.edu.sdjzu.exception.BysjException;
import cn.edu.sdjzu.xg2106.dao.DepartmentDao;
import cn.edu.sdjzu.xg2106.domain.Department;
import cn.edu.sdjzu.xg2106.domain.School;
import cn.edu.sdjzu.xg2106.util.Condition;
import cn.edu.sdjzu.xg2106.util.JdbcHelper;
import cn.edu.sdjzu.xg2106.util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public class DepartmentService {
    public static DepartmentDao departmentDao = DepartmentDao.getInstance();
    private static DepartmentService departmentService=null;
    private DepartmentService(){}
    public static DepartmentService getInstance(){
        if (departmentService == null){
            departmentService=new DepartmentService();
        }
        return departmentService;
    }
    public void add(Department department) throws SQLException {
        departmentDao.add(department);
    }
    public void update(Department department) throws SQLException {
        departmentDao.update(department);
    }
    public Collection<Department> findAll(Pagination pagination, List<Condition> conditionList) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Collection<Department> deps = departmentDao.findAll(connection,conditionList,pagination);
        JdbcHelper.close(connection);
        return deps;
    }
    public Department find(int id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Department department = departmentDao.find(connection,id);
        JdbcHelper.close(connection);
        return department;
    }

    public int countAll(School school) throws SQLException{
        Connection connection = JdbcHelper.getConn();
        int department = departmentDao.countAll(school);
        JdbcHelper.close(connection);
        return department;
    }
    public void delete(int id) throws SQLException, BysjException, ClassNotFoundException {
        Department departmentToDelete = DepartmentService.getInstance().find(id);
        int countTeachersOfDepartment = TeacherService.getInstance().countAll(departmentToDelete);
        if (countTeachersOfDepartment==0){
            departmentDao.delete(id);
        }else {
            throw new BysjException(departmentToDelete.getDescription() + "仍有下属系，不可删除");
        }
    }

}
